package com.simdo.g768.Mqtt;

import android.content.Context;
import android.content.res.AssetManager;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;

import info.mqtt.android.service.MqttAndroidClient;

public class MqttConnection {

    private final boolean tls;

    private final Context context;

    public MqttBean getMqttBean() {
        return mqttBean;
    }

    private final MqttBean mqttBean;

    public MqttConnection(Context context, MqttBean mqttBean, boolean tls) {
        this.context = context;
        this.mqttBean = mqttBean;
        this.tls = tls;
    }

    public MqttAndroidClient getMqttAndroidClient() {
        String uri = (tls ? "ssl://" : "tcp://") + mqttBean.getHost() + ":" + mqttBean.getPort();
        return new MqttAndroidClient(context, uri, "app_client");

    }

    public MqttConnectOptions getMqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setAutomaticReconnect(false);
        options.setKeepAliveInterval(60);
        if (tls) {
            try {
                AssetManager am = context.getAssets();
                options.setSocketFactory(SSLUtils.getSingleSocketFactory(am.open("ca.crt")));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (!mqttBean.getUsername().isEmpty()) options.setUserName(mqttBean.getUsername());

        if (!mqttBean.getPassword().isEmpty()) options.setPassword(mqttBean.getPassword().toCharArray());

        return options;
    }
}
